package org.dbcopy.service;

import org.dbcopy.domain.ApplicationParameters;
import org.dbcopy.domain.Table;
import org.dbcopy.util.DbUtils;
import org.dbcopy.util.FileUtils;

import java.sql.*;
import java.util.*;

public class Exporter{
	Connection connection;
	ApplicationParameters properties;
	public Exporter(ApplicationParameters ap){
		properties = ap;
	}

    public List<Table> fetchDbTables() {
        List<Table> allTables = null;
        try{
            DbUtils utils = new DbUtils(properties);
            connection = utils.openConnection();
            allTables = utils.getAllTables();
            for (Table table : allTables){
                ResultSet statementResult = utils.getAllData(table);
                int lineNumber = 0;
                System.out.println("Table Name -> " + table.getName());
                ResultSetMetaData md = statementResult.getMetaData();
                for (int j = 1; j <= md.getColumnCount(); j++) {
                    table.addColumn(md.getColumnName(j));
                }
                while (statementResult.next()) {
                    int cols = md.getColumnCount();
                    for (int i = 1; i <= cols; i++) {
                        table.addRow(statementResult.getObject(i), lineNumber);
                        System.out.print(statementResult.getObject(i) + " ");
                    }
                    lineNumber++;
                    System.out.println();
                }
            }
            utils.closeConnection();
        } catch (Exception e)	{
            System.err.println("Unable to perform database statement");
            e.printStackTrace();
        }
        return allTables;
    }
    
    public void saveDbTables(List<Table> tableList) {
        FileUtils fu = new FileUtils("%03d-%s.csv");
        for (Table table : tableList) {
            fu.saveTable(table);
        }
        fu.zipTables(tableList, properties.getZipPath());
    }

	public void doExport(){
        saveDbTables(fetchDbTables());
	}
} 